package com.gzy.rpsm_property.controller;

import com.gzy.rpsm_property.pojo.Attention;
import com.gzy.rpsm_property.pojo.ResponsePojo;
import com.gzy.rpsm_property.pojo.User;
import com.gzy.rpsm_property.pojo.Users;
import com.gzy.rpsm_property.service.AttentionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;


@RestController
@Api(tags = "关注相关API")
public class AttentionController {

    @Autowired
    private AttentionService attentionService;
    private static final Logger logger = LoggerFactory.getLogger(AttentionController.class);
    private static final String FOLLOW_SUCCESS_MESSAGE = "关注成功";
    private static final String FOLLOW_FAILURE_MESSAGE = "关注失败，用户不存在或已经关注过该用户";

//    @PostMapping("/attention/add")
//    @ApiOperation(value = "根据用户名添加关注关系")
//    public String addAttention(
//            @RequestParam(value = "fromUsername") String fromUsername,
//            @RequestParam(value = "toUsername") String toUsername) {
//        attentionService.addAttention(fromUsername, toUsername);
//        return "关注成功";
//    }
@GetMapping("/list")
@ApiOperation(value = "获取关注列表", notes = "获取所有关注关系列表")
@ApiResponses({
        @ApiResponse(code = 200, message = "成功获取关注列表"),
        @ApiResponse(code = 500, message = "系统错误")
})
public ResponseEntity<List<Map<String, Object>>> getAttentionList() {
    try {
        logger.info("Request received to get attention list");
        List<Map<String, Object>> attentionList = attentionService.getAttentionList();
        if (attentionList == null || attentionList.isEmpty()) {
            logger.warn("No attention records found");
            return ResponseEntity.status(HttpStatus.NO_CONTENT).body(attentionList);
        }
        return ResponseEntity.ok(attentionList);
    } catch (Exception e) {
        logger.error("Error occurred while getting attention list", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
}

    @GetMapping("/getFollowingUsersByUsername")
    @ApiOperation(value = "获取指定用户的关注列表", notes = "根据用户名获取该用户关注的所有用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功获取关注列表"),
            @ApiResponse(code = 400, message = "请求参数无效"),
            @ApiResponse(code = 404, message = "用户不存在"),
            @ApiResponse(code = 500, message = "系统错误")
    })
    public ResponseEntity<List<Users>> getFollowingUsersByUsername(
            @RequestParam @NotBlank(message = "用户名不能为空") String username) {
        try {
            logger.info("Request received to get following users for user: {}", username);
            List<Users> followingUsers = attentionService.getFollowingUsersByUsername(username);
            if (followingUsers == null || followingUsers.isEmpty()) {
                logger.warn("No following users found for user: {}", username);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            return ResponseEntity.ok(followingUsers);
        } catch (IllegalArgumentException e) {
            logger.error("Invalid request parameter for user: {}", username, e);
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            logger.error("Error occurred while getting following users for user: {}", username, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @GetMapping("/getFollowersByUsername")
    @ApiOperation(value = "获取指定用户的粉丝列表", notes = "根据用户名获取该用户的所有粉丝")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功获取粉丝列表"),
            @ApiResponse(code = 400, message = "请求参数无效"),
            @ApiResponse(code = 404, message = "用户不存在"),
            @ApiResponse(code = 500, message = "系统错误")
    })
    public ResponseEntity<List<Users>> getFollowersByUsername(
            @RequestParam @NotBlank(message = "用户名不能为空") String username) {
        try {
            logger.info("Request received to get followers for user: {}", username);
            List<Users> followers = attentionService.getFollowersByUsername(username);
            if (followers == null || followers.isEmpty()) {
                logger.warn("No followers found for user: {}", username);

                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            return ResponseEntity.ok(followers);
        } catch (IllegalArgumentException e) {
            logger.error("Invalid request parameter for user: {}", username, e);
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            logger.error("Error occurred while getting followers for user: {}", username, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @PostMapping("/follow")
    @ApiOperation(value = "关注用户", notes = "根据用户名关注另一个用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = FOLLOW_SUCCESS_MESSAGE),
            @ApiResponse(code = 400, message = FOLLOW_FAILURE_MESSAGE)
    })
    public ResponseEntity<ResponsePojo<Void>> followUser(
            @RequestParam @NotBlank(message = "关注者用户名不能为空") String followerUsername,
            @RequestParam @NotBlank(message = "被关注者用户名不能为空") String followingUsername) {
        if (followerUsername.equals(followingUsername)) {
            return ResponseEntity.badRequest().body(ResponsePojo.fail(null, "不能关注自己"));
        }

        try {
            logger.info("Request received to follow user: {} by user: {}", followingUsername, followerUsername);
            ResponsePojo<Void> response = attentionService.followUser(followerUsername, followingUsername);
            return handleResponse(response);
        } catch (Exception e) {
            logger.error("Error occurred while following user: {} by user: {}", followingUsername, followerUsername, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponsePojo.fail(null, "系统错误"));
        }
    }

    private ResponseEntity<ResponsePojo<Void>> handleResponse(ResponsePojo<Void> response) {
        if (response.getSuccess()) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body(response);
        }
    }

}
